import ApiFetchers from "@/apis/api_fetchers"
import { createLogger } from "@/utils/logger"
import styled from "@emotion/styled"
import { useCallback, useEffect, useState } from "react"
import { useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom"
import { toast } from "react-toastify"
import { Menu } from "./components/Menu"
const logger = createLogger("GamePage")

const Container = styled.div`
    background-color: #000;
    width: 100%;
    flex: 1;
    display: flex;
    flex-direction: column;
`

const Iframe = styled.iframe`
    border: 0 none;
    width: 100%;
    flex: 1;
    position: relative;
`

function GamePage() {
    const location = useLocation()
    const navigate = useNavigate()
    const { gameName = "" } = useParams()
    const [searchParams] = useSearchParams()
    const [url, setUrl] = useState<string>("")
    const { content = "" } = location.state ? location.state : {}
    const getGameUrl = useCallback(async (name: string) => {
        const url = await ApiFetchers.refGetGameLaunch({
            code: name,
        })
        if (url.startsWith("http")) {
            return setUrl(url)
        }
        toast.error(url || "error")
    }, [])

    useEffect(() => {
        const _url = searchParams.get("game_url")
        if (_url) {
            setUrl(_url)
            navigate(
                {
                    pathname: location.pathname,
                    search: ``,
                },
                {
                    state: location.state, // 保留原 state
                    replace: true,
                },
            )
            return
        }
        if (!content) {
            getGameUrl(gameName)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [gameName])

    logger.debug("url", url)
    logger.debug("location.state", location.state)

    return (
        <Container>
            <Menu />
            <Iframe
                title={gameName}
                src={url || content}
                loading="lazy"
            />
        </Container>
    )
}

export default GamePage
